#include "systick.h"
#include "modbus.h"
#include "device.h"
#include "tim.h"
#include "wwdg.h"
#include "can.h"
#include "gpio.h"
#include "usart.h"


unsigned char server_address;

UU16 system_tick = {0};

void Read_Address(void)
{
    server_address = 0x0D;
}

ushort SystemTickLow()
{
    ushort tick = timer_counter_read(TIMER6);
    return tick;
}

ushort SystemTickHigh()
{
    uchar hi, lo;

    do
    {
        hi = system_tick.UU8[MSB];
        lo = system_tick.UU8[LSB];
    }
    while(hi != system_tick.UU8[MSB]);

    return (ushort)hi << 8 | lo;
}

ulong SystemTick()
{
    ushort hi, lo;
    do
    {
        hi = SystemTickHigh();
        lo = SystemTickLow();
    }
    while(hi != SystemTickHigh());

    return (ulong)hi << 16 | lo;
}

void Delay_Tick(ushort tick)
{
    ushort t = SystemTickLow();
    while((ushort)(SystemTickLow() - t) < tick)
        Update_WatchDog();
}

void Delay_Tick_Event(ulong tick)
{
    ulong t = SystemTick();
    while(SystemTick() - t < tick)
        Main_Loop();
}

void Delay_Tick_Loop(ulong tick)
{
    ulong t = SystemTick();
    while((SystemTick() - t) < tick)
    {
        Main_Loop();
    }
}



void Delay_ms(uint32_t count)
{
   Delay_Tick_Loop(count*1000);
}

void Device_Init(void)
{
    systick_config();
    Read_Address();
    MX_GPIO_Init();
    Usart0_Init();
    //CAN_Init();
    MX_TIM0_Init(); //Y电机 STEP
    MX_TIM1_Init(); //M电机 STEP
    MX_TIM2_Init(); //Z电机 STEP
    MX_TIM3_Init(); //X电机 STEP
    MX_TIM5_Init(); //485接收
    MX_TIM6_Init(); //计时


// #if USE_WATCHDG
//     MX_WWDG_Init();
// #endif
}
